package com.nfit.shopweb.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.nfit.shopmodel.vo.product.CategoryExcelVo;
import com.nfit.shopweb.mapper.CategoryMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:CategoryListener
 * Package:com.nfit.shopweb.listener
 * Description
 *easy Excel 监听器
 * @Author L
 * @Create 2024/12/11 8:46
 */
@Slf4j
public class CategoryListener<T> implements ReadListener<T> {

    private static final Integer COUNT = 100;

    private List list = ListUtils.newArrayListWithExpectedSize(COUNT);

    private CategoryMapper categoryMapper;
    /**
     * 构造方法注入
     * @param categoryMapper
     */
    public CategoryListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }



    /**
     * 这个每一条数据解析都会来调用
     *
     * @param t    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(T t, AnalysisContext context) {
        CategoryExcelVo categoryExcelVo = (CategoryExcelVo) t;
        log.info("解析到一条数据:{}", JSON.toJSONString(categoryExcelVo));
        list.add(categoryExcelVo);
        if(list.size() >= COUNT){
            //调用封装好的方法,把数据添加到数据库
            saveData();
            //重新初始化list
            list = ListUtils.newArrayListWithExpectedSize(COUNT);
        }

    }


    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        categoryMapper.exportSave(list);
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        categoryMapper.exportSave(list);
        log.info("存储数据库成功！");
    }
}
